package com.wzy.quartz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wzy.constant.SystemConstants;
import com.wzy.domain.entity.Article;
import com.wzy.mapper.ArticleMapper;
import com.wzy.service.ArticleCommonService;
import com.wzy.util.RedisCache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.wzy.constant.RedisConstants.REDIS_ARTICLE_VIEW_KEY;

/**
 * 持久化浏览量定时任务
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class PersistentTask
{
    private final ArticleMapper articleMapper;
    private final RedisCache redisCache;
    private final ArticleCommonService articleCommonService;

    /**
     * 持久化浏览量定时任务，每隔十分钟执行一次
     */
    @Scheduled(cron = "0 0/10 * * * ? ")
    public void redisToMysql()
    {
        log.info("---------开始持久化浏览量---------");
        List<Article> articles = articleMapper.selectList(new LambdaQueryWrapper<Article>()
                .eq(Article::getArticleStatus, SystemConstants.RELEASE));

        articles.forEach(article ->
        {
            Long id = article.getId();
            String redisKey = REDIS_ARTICLE_VIEW_KEY + id.toString();
            String viewCount = redisCache.getCacheObject(redisKey).toString();
            log.info("{}-浏览量:{}", redisKey, viewCount);
            article.setViewCount(Long.valueOf(viewCount));
            articleMapper.updateById(article);
        });
        log.info("---------持久化浏览量完成---------");
    }

    /**
     * 更新文章列表定时任务，每隔十分钟执行一次
     */
    @Scheduled(cron = "0 0/10 * * * ? ")
    public void updateRedisArticle()
    {
        log.info("---------开始更新文章列表---------");
        articleCommonService.redisArticleList();
        log.info("---------更新文章列表完成---------");
    }

}
